package com.dhms.vostok1.ui.login

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.dhms.vostok1.MainApplication
import com.dhms.basebusiness.R
import com.dhms.vostok1.data.ApiState
import com.dhms.vostok1.databinding.FragmentLoginBinding
import com.dhms.vostok1.model.StartingViewModel
import com.dhms.vostok1.model.UserViewModel
import com.dhms.vostok1.repository.CheckInstrumentRepository
import com.dhms.vostok1.repository.FaultRepository
import com.dhms.vostok1.ui.main.MainActivity
import com.dhms.vostok1.utils.isEndIconVisible
import com.permissionx.guolindev.PermissionX

val PHONE_NUMBER_REGEX =
    """^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$""".toRegex()

class LoginFragment : Fragment() {

    private var _binding: FragmentLoginBinding? = null
    private val binding get() = _binding!!

    private val userViewModel: UserViewModel by activityViewModels()
    private val startingViewModel: StartingViewModel by lazy {
        StartingViewModel(
            FaultRepository.getInstance((requireActivity().application as MainApplication).database.faultDao()),
            CheckInstrumentRepository.getInstance(
                (requireActivity().application as MainApplication).database.checkInstrumentDao()
            )
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLoginBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.viewModel = userViewModel
        binding.lifecycleOwner = viewLifecycleOwner

        binding.loginSubmit.text = "登录"
        binding.loginSubmit.post {
            binding.loginSubmit.isEnabled = false
        }

        binding.username.hint = getString(R.string.username_placeholder)
        binding.password.hint = getString(R.string.password_placeholder)
        binding.verificationCode.hint = getString(R.string.verification_code_placeholder)
        binding.username.setOnFocusChangeListener { _, hasFocus ->
            if (!hasFocus) {
                binding.username.hint = getString(R.string.username_placeholder)
            } else {
                binding.username.hint = ""
            }
            binding.usernameWrapper.isEndIconVisible = binding.username.isEndIconVisible(hasFocus)
        }
        binding.password.setOnFocusChangeListener { _, hasFocus ->
            if (!hasFocus) {
                binding.password.hint = getString(R.string.password_placeholder)
            } else {
                binding.password.hint = ""
            }
        }
        binding.verificationCode.setOnFocusChangeListener { _, hasFocus ->
            if (!hasFocus) {
                binding.verificationCode.hint = getString(R.string.verification_code_placeholder)
            } else {
                binding.verificationCode.hint = ""
            }
            binding.verificationCodeWrapper.isEndIconVisible =
                binding.verificationCode.isEndIconVisible(hasFocus)
        }
        binding.username.addTextChangedListener {
            binding.usernameWrapper.error = null
        }
        binding.password.addTextChangedListener({ text, start, count, after ->

        }, { text, start, before, count ->
            text?.let {
                binding.loginSubmit.isEnabled = it.length >= 6 && binding.username.text.isNotEmpty()
                if (it.length >= 6) {
                    binding.loginSubmit.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.dhms.uikit.R.color.white_color
                        )
                    )
                } else {
                    binding.loginSubmit.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            R.color.theme_light_tertiary
                        )
                    )
                }
            }
        }, {
            binding.passwordWrapper.error = null
        }
        )

        binding.verificationCode.addTextChangedListener {
            binding.verificationCodeWrapper.error = null
        }
        binding.loginWithVerificationCode.text = getString(R.string.login_with_verification_code)
        binding.loginWithVerificationCode.setOnClickListener {
            userViewModel.switchLoginMethod()
        }

        userViewModel.loginResult.observe(viewLifecycleOwner) { loginResult ->
            when (loginResult?.state) {
                ApiState.DONE -> {
                    startingViewModel.prepareData()
                    Toast.makeText(requireContext(), "登录成功！", Toast.LENGTH_SHORT).show()
                    val intent = Intent(
                        requireContext(),
                        MainActivity::class.java
                    ).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                }
                ApiState.ERROR -> {
                    errorTip(loginResult.message)
                }
                ApiState.LOADING -> {}
                else -> {}
            }
            binding.loginSubmit.text =
                if (loginResult?.state == ApiState.LOADING) getString(R.string.login_submitting) else getString(
                    R.string.login_submit
                )
            binding.loginSubmit.isEnabled = loginResult?.state != ApiState.LOADING
        }

        binding.loginSubmit.setOnClickListener {
            val username = binding.username.text
            val password = binding.password.text
            val verifyCode = binding.verificationCode.text
            var formCheckPassed = true
            if (username.isEmpty()) {
                binding.usernameWrapper.error = "用户名不能为空！"
                formCheckPassed = false
            } else if (!PHONE_NUMBER_REGEX.matches(username)) {
                binding.usernameWrapper.error = "手机号格式有误！"
                formCheckPassed = false
            }
            if (userViewModel.isMessageLogin.value == true) {
                if (verifyCode.length < 6) {
                    binding.verificationCodeWrapper.error = "验证码为6位！"
                    formCheckPassed = false
                }
            } else {
                if (password.isEmpty()) {
                    binding.passwordWrapper.error = "密码不能为空！"
                    formCheckPassed = false
                }
            }

            if (!formCheckPassed) return@setOnClickListener

            PermissionX.init(this)
                .permissions(Manifest.permission.INTERNET)
                .request { allGranted, _, _ ->
                    if (allGranted) {
                        if (userViewModel.isMessageLogin.value == true) {
                            userViewModel.messageLogin(
                                username.toString(),
                                verifyCode.toString()
                            )
                        } else {
                            userViewModel.login(username.toString(), password.toString())
                        }
                    } else {
                        Toast.makeText(requireContext(), "请先授予网络权限！", Toast.LENGTH_SHORT).show()
                    }
                }
        }

        binding.sendVerificationCode.setOnClickListener {
            val username = binding.username.text
            if (username.isEmpty()) {
                binding.usernameWrapper.error = "账号不能为空！"
                return@setOnClickListener
            }
            if (!PHONE_NUMBER_REGEX.matches(username)) {
                binding.usernameWrapper.error = "手机号格式有误！"
                return@setOnClickListener
            }

            userViewModel.sendVerifyCode(username.toString())
        }

        userViewModel.sendVerifyCodeResult.observe(viewLifecycleOwner) { sendResult ->
            if (sendResult?.state == ApiState.ERROR) {
                errorTip(sendResult.message)
            }
        }

        binding.resetPassword.setOnClickListener {
            try {
                findNavController().navigate(R.id.action_loginFragment_to_resetPasswordFragment)
            } catch (ex: Exception) {
            }
        }

        binding.aboutEntrance.setOnClickListener {
            try {
                findNavController().navigate(R.id.action_loginFragment_to_aboutFragmentInLogin)
            } catch (ex: Exception) {
            }
        }
    }

    private fun errorTip(message: String?) {
        (activity as LoginActivity).showToast(
            com.dhms.vostok1.R.drawable.ic_fail,
            message,
            false,
            1
        )
    }

    companion object {
        private const val TAG = "LoginFragment"
    }
}